<?php


namespace App\Models;


use App\Common\AuthService;
use EasySwoole\Component\Singleton;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\AbstractModel;
use PhpParser\Node\Scalar\MagicConst\Dir;

class MenuModel extends BaseModel
{
    use Singleton;
    protected $tableName = 'system_menu';

    /**
     * @param $menuId int 栏目ID 父亲的id
     * @return array
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * 获取儿子栏目
     */
    public function getChildrenMenus(int $menuId)
    {
        $field = 'id, pid, title, icon, href, spread, target,params';
        //获取顶级菜单栏目
        $first_menu = $this->field($field)->where(['pid' => $menuId, 'status' => 1])
            ->order('sort', 'asc')->order('create_at', 'desc')->select();
        return $first_menu;
    }

    /**
     * @return array
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * 获取顶级菜单
     */
    public function getMenuList()
    {
        //查询顶级菜单栏数据
        $nav = $this->getNav();
        //去除空菜单栏目
        foreach ($nav as $k => $val) {
            $menu = $this->where(['pid' => $val['id'], 'status' => 1])->select();
            if (empty($menu)) {
                unset($nav[$k]);
            };
        }
        //判断图标类型
//        foreach ($nav as $key => $val){
//            (strpos($nav[$key]['icon'], 'fa-') !== false) ? $nav[$key]['icon_type'] = true : $nav[$key]['icon_type'] = false;
//        }
        return $nav;
    }

    public function getAllMenu()
    {
        $nav = $this->getNav();
        $nav = array_combine(array_column($nav, 'id'), $nav);
        $list = $this->field('id, title, icon,pid,node,href,sort,status')
            ->order('sort,id', 'asc')->select(function (QueryBuilder $query) {
                $query->where('pid', '0', '<>');
            });
        $map = array_combine(array_column($list, 'id'), $list);
        foreach ($list as $item) {
            if (isset($item['pid']) && isset($map[$item['pid']])) {
                $map[$item['pid']]['sub'][] = &$map[$item['id']];
            } else {
                if (isset($nav[$item['pid']])) {
                    $nav[$item['pid']]['sub'][] =  &$map[$item['id']];
                }
            }
        }
        return $nav;
    }

    private function getNav()
    {
        $nav = $this->where(['pid' => 0, 'status' => 1])
            ->field('id, title, icon,pid,node,href,sort,status,params')
            ->select(function (QueryBuilder $query) {
                $query->where('id', 1, '<>')->orderBy('sort,create_at', 'asc');
            });
        return $nav;
    }


}
